<?php

/**
 * this class help to parse email content var and send mail directly using email function or smtp mail base on phpmailer
 */
class EmailHelper {

    /**
     * send mail for successfull registration
     */
    public static function sendMailResgistration($receiptContent) {
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 1')
		->queryRow();

	$body = str_replace(
		array('[NAME]', '[SITE_NAME]', '[LINK]', '[URL]'), array(
	    $receiptContent['name'],
	    settings()->get('site', 'name'),
	    SITE_NAME_URL . 'site/activekey/key/' . $receiptContent['activationKey'],
	    SITE_NAME_URL
		), $mailTemplate['body']
	);
	self::send($receiptContent['emailReceive'], $mailTemplate['subject'], $body);
    }

    /**
     * send email using newsletter template
     * @param string $receiver receiver email
     */
    public static function sendNewsletter($receiver) {
	
    }

    /**
     * send mail after custommer click submit contact form
     * @param mix $receiptContent array or object,
     * array('subject' => 'message', 'body' => 'body', 'email' => email, 'phone' => 'phone')
     */
    public static function sendContactRequest($receiptContent) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 10')
		->queryRow();

	if (is_array($receiptContent)) {
	    $body = str_replace(array('[MESSAGE]', '[SENDER]', '[NAME]', '[PHONE]', '[MAILSUBJECT]', '[IP]', '[SITE_NAME]', '[URL]'), array(
		$receiptContent['body'],
		$receiptContent['email'],
		$receiptContent['name'],
		$receiptContent['phone'],
		$receiptContent['subject'],
		$_SERVER['REMOTE_ADDR'],
		'Contact',
		bu()
		    ), $mailTemplate['body']
	    );
	} elseif (is_object($receiptContent)) {
	    $body = str_replace(array('[MESSAGE]', '[SENDER]', '[NAME]', '[PHONE]', '[MAILSUBJECT]', '[IP]', '[SITE_NAME]', '[URL]'), array(
		$receiptContent->body,
		$receiptContent->email,
		$receiptContent->name,
		$receiptContent->phone,
		$receiptContent->subject,
		$_SERVER['REMOTE_ADDR'],
		'Contact',
		bu()
		    ), $mailTemplate['body']
	    );
	} else {
	    //model not valid
	    throw new CHttpException(500, 'receiver MUST be CFormModel or array');
	    return;
	}
	//send mail to admin
	$adminEmail = app()->settings->get('site', 'admin_email');
	self::send($adminEmail, $receiptContent['subject'], $body);
    }

    /**
     * send the request password to user email
     * @param type $resceipt
     * @param type $url
     */
    public static function sendForgotPassword($resceipt) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 2')
		->queryRow();

	$body = str_replace(array('[SITE_NAME]', '[EMAIL]', '[NEWPASS]', '[URL]'), array(
	    settings()->get('site', 'name'),
	    $resceipt['email'],
	    $resceipt['pass'],
	    SITE_NAME_URL,
		), $mailTemplate['body']
	);
	self::send($resceipt['email'], $mailTemplate['subject'], $body);
    }

    /**
     * send mail for birthday
     */
    public static function sendMailForBirth($resceipt) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 3')
		->queryRow();
	$body = str_replace(array('[SITE_NAME]', '[USERNAME]', '[URL]'), array(
	    settings()->get('site', 'name'),
	    $resceipt['username'],
	    SITE_NAME_URL,
		), $mailTemplate['body']
	);
	self::send($resceipt['email'], $mailTemplate['subject'], $body);
    }

    /**
     * send mail  for match
     */
    public static function sendmailFormatch($receipt) {
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 4')
		->queryRow();
	$listPerson = '<ul>';
	foreach ($receipt['listUsers'] as $user) {
	    $listPerson .= '<li><a href="' . SITE_NAME_URL . 'user/' . $user['user_id'] . '">' . $user['username'] . ' - Age: ' . $user['age'] . '</a></li>';
	}
	$listPerson .= '</ul>';
	$body = str_replace(array('[SITE_NAME]', '[USERNAME]', '[LIST_PERSON]', '[URL]'), array(
	    settings()->get('site', 'name'),
	    $receipt['username'],
	    $listPerson,
	    SITE_NAME_URL
		), $mailTemplate['body']
	);
	self::send($receipt['email'], $mailTemplate['subject'], $body);
    }

    /**
     * send mail to reveiver
     * @param string $receiver email
     * @param string $subject
     * @param string $body
     */
    public static function send($receipt, $subject, $body = '', $recipientName = '') {

	//reading config
	$setting = app()->settings;
	$emailConfig = $setting->load('email');
	$adminEmail = $setting->get('site', 'admin_email');
//
//	if ($emailConfig['smtp']) { //using smtp email
//	    //load phpmailer class
//	    Yii::import('common.extensions.swiftMailer.SwiftMailer');
//
//	    $mailer = new SwiftMailer;
//	    $mailer->init();
//	    // Get config
//	    $mailHost = $emailConfig['smtp_host'];
//	    $mailPort = $emailConfig['smtp_port']; // Optional
//	    // New transport
//	    $Transport = $mailer->smtpTransport($mailHost, $mailPort);
//
//	    // Mailer
//	    $Mailer = $mailer->mailer($Transport);
//
//	    // New message
//	    $Message = $mailer
//		    ->newMessage($subject)
//		    ->setFrom(array($adminEmail => $adminEmail))
//		    ->setTo(array($receipt => $recipientName))
//		    ->addPart($body, 'text/html')
//		    ->setBody($body);
//
//	    // Send mail
//	    $Mailer->send($Message);
//	} else { //using email() function
	// To send HTML mail, the Content-type header must be set
//	$headers = 'MIME-Version: 1.0' . "\r\n";
//	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
//	$headers = "From: {$adminEmail}\r\nReply-To: {$adminEmail}";
//	$message = '<html>
//		    <head>
//		      <title>' . $subject . '</title>
//		    </head>
//		    <body>' . $body . '</body>
//		    </html>';
//	mail($receipt, $subject, $message, $headers);
//	}

	$message = '
		    <html>
		    <head>
		      <title>Birthday Reminders for August</title>
		    </head>
		    <body>
		      ' . $body . '
		    </body>
		    </html>
		    ';

	$headers = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	$headers .= 'From:  <' . $adminEmail . '>' . "\r\n";
	$subject = '[' . settings()->get('site', 'name') . ']' . $subject;
	mail($receipt, $subject, $message, $headers);
    }

    /**
     * 
     * @param type $from
     * @param type $to
     * @param type $subject
     * @param type $body
     * @param type $recipientName
     */
    public static function send_from_to($from, $to, $subject, $body = '', $recipientName = '') {
	//reading config
	$setting = app()->settings;
	$emailConfig = $setting->load('email');
	$adminEmail = $from;

	if ($emailConfig['smtp']) { //using smtp email
	    //load phpmailer class
	    Yii::import('common.extensions.swiftMailer.SwiftMailer');

	    $mailer = new SwiftMailer;
	    $mailer->init();
	    // Get config
	    $mailHost = $emailConfig['smtp_host'];
	    $mailPort = $emailConfig['smtp_port']; // Optional
	    // New transport
	    $Transport = $mailer->smtpTransport($mailHost, $mailPort);

	    // Mailer
	    $Mailer = $mailer->mailer($Transport);

	    // New message
	    $Message = $mailer
		    ->newMessage($subject)
		    ->setFrom(array($adminEmail => $adminEmail))
		    ->setTo(array($receipt => $to))
		    //->addPart($body, 'text/html')
		    ->setBody($body, 'text/html');

	    // Send mail
	    $Mailer->send($Message);
	} else { //using email() function
	    $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	    $headers .= "From: {$adminEmail}\r\nReply-To: {$adminEmail}";
	    mail($to, $subject, $body, $headers);
	}
    }

    /**
     * send for reactive ads
     * @param type $resceipt
     * @param type $url
     */
    public static function sendReactive($resceipt, $username, $urlActive) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 6')
		->queryRow();
	$url = "<a href='" . SITE_NAME_URL . "'> " . SITE_NAME_URL . "</a>";

	$body = str_replace(array('[SITE_NAME]', '[NAME]', '[URL_ACTIVE]', '[URL]'), array(
	settings()->get('site', 'name')
	$username,
	$urlActive,
	$url
	), $mailTemplate['body']
	);

	self::send($resceipt, $mailTemplate['subject'], $body);
    }

    /**
     * send for reactive ads
     * @param type $resceipt
     * @param type $url
     */
    public static function sendReactiveBefore($resceipt, $username, $urlActive) {
	//get email template
	$mailTemplate = db()->createCommand()
		->select('*')
		->from('{{email_templates}}')
		->where('id = 5')
		->queryRow();
	$url = "<a href='" . SITE_NAME_URL . "'> " . SITE_NAME_URL . "</a>";

	$body = str_replace(array('[SITE_NAME]', '[NAME]', '[URL_ACTIVE]', '[URL]'), array(
	settings()->get('site', 'name')
	$username,
	$urlActive,
	$url
	), $mailTemplate['body']
	);

	self::send($resceipt, $mailTemplate['subject'], $body);
    }

}

